package org.example.hospital_frontend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.hospital_frontend.common.Result;
import org.example.hospital_frontend.domain.Register;
import org.example.hospital_frontend.domain.User;
import org.example.hospital_frontend.service.RegisterService;
import org.example.hospital_frontend.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("/register")
public class RegisterController {

    @Autowired
    private RegisterService registerService;
    @Autowired
    private UserService userService;

    // 查询当前用户挂号列表（分页，带医生姓名）
    @GetMapping("/user/list")
    public Result<Page<Map<String, Object>>> getUserRegisterList(
            HttpServletRequest request,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        User currentUser = (User) request.getSession().getAttribute("USER_LOGIN_STATE");
        if (currentUser == null) {
            return Result.error("无权限");
        }
        QueryWrapper<Register> qw = new QueryWrapper<>();
        qw.eq("user_id", currentUser.getId());
        qw.orderByDesc("register_time");
        Page<Register> page = registerService.page(new Page<>(pageNum, pageSize), qw);

        // 拼装医生姓名
        List<Map<String, Object>> records = new ArrayList<>();
        for (Register reg : page.getRecords()) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", reg.getId());
            map.put("doctorId", reg.getDoctorId());
            map.put("registerTime", reg.getRegisterTime());
            map.put("status", reg.getStatus());
            // 查医生姓名
            User doctor = userService.getById(reg.getDoctorId());
            map.put("doctorUsername", doctor != null ? doctor.getUsername() : "未知医生");
            records.add(map);
        }
        Page<Map<String, Object>> resultPage = new Page<>();
        resultPage.setRecords(records);
        resultPage.setTotal(page.getTotal());
        resultPage.setCurrent(page.getCurrent());
        resultPage.setSize(page.getSize());
        return Result.success(resultPage);
    }

    // 新增挂号
    @PostMapping("/user/add")
    public Result addRegister(@RequestBody Map<String, Object> req, HttpServletRequest request) {
        User currentUser = (User) request.getSession().getAttribute("USER_LOGIN_STATE");
        if (currentUser == null) {
            return Result.error("无权限");
        }
        Integer doctorId = Integer.parseInt(req.get("doctorId").toString());

        if (doctorId == null) return Result.error("请选择医生");
        Register reg = new Register();
        reg.setUserId(currentUser.getId());
        reg.setDoctorId(doctorId);
        reg.setRegisterTime(new Date());
        reg.setStatus(0L);
        registerService.save(reg);
        return Result.success();
    }

    // 查询单条挂号
    @GetMapping("/user/{id}")
    public Result<Map<String, Object>> getRegisterById(@PathVariable Integer id, HttpServletRequest request) {
        User currentUser = (User) request.getSession().getAttribute("USER_LOGIN_STATE");
        if (currentUser == null) {
            return Result.error("无权限");
        }
        Register reg = registerService.getById(id);
        if (reg == null || !reg.getUserId().equals(currentUser.getId())) {
            return Result.error("无权访问");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("id", reg.getId());
        map.put("doctorId", reg.getDoctorId());
        map.put("registerTime", reg.getRegisterTime());
        map.put("status", reg.getStatus());
        User doctor = userService.getById(reg.getDoctorId());
        map.put("doctorUsername", doctor != null ? doctor.getUsername() : "未知医生");
        return Result.success(map);
    }

    // 编辑挂号
    @PostMapping("/user/update")
    public Result updateRegister(@RequestBody Map<String, Object> req, HttpServletRequest request) {
        User currentUser = (User) request.getSession().getAttribute("USER_LOGIN_STATE");
        if (currentUser == null) {
            return Result.error("无权限");
        }
        Integer id = Integer.parseInt(req.get("id").toString());
        Integer doctorId = Integer.parseInt(req.get("doctorId").toString());
        if (id == null || doctorId == null) return Result.error("参数错误");
        Register reg = registerService.getById(id);
        if (reg == null || !reg.getUserId().equals(currentUser.getId())) {
            return Result.error("无权操作");
        }
        reg.setDoctorId(doctorId);
        registerService.updateById(reg);
        return Result.success();
    }

    // 查询所有医生
    @GetMapping("/doctor/list")
    public Result<List<Map<String, Object>>> getDoctorList() {
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("role", 2);
        List<User> doctors = userService.list(qw);
        List<Map<String, Object>> result = new ArrayList<>();
        for (User doc : doctors) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", doc.getId());
            map.put("username", doc.getUsername());
            result.add(map);
        }
        return Result.success(result);
    }

    // 删除挂号
    @DeleteMapping("/user/delete/{id}")
    public Result deleteRegister(@PathVariable Integer id, HttpServletRequest request) {
        User currentUser = (User) request.getSession().getAttribute("USER_LOGIN_STATE");
        if (currentUser == null) {
            return Result.error("无权限");
        }
        Register reg = registerService.getById(id);
        if (reg == null || !reg.getUserId().equals(currentUser.getId())) {
            return Result.error("无权操作");
        }
        registerService.removeById(id);
        return Result.success();
    }
}